/* 
 * $Id$
 */

var dict = angular.module("app-dict", []);

dict.factory("uws", function() { // user words service
    var the_word = word;
    var user_entries = [];
    return {"set_word"   : function(w) {the_word = w;},

            "word"       : function() {return the_word;},

            "definition" : function() {
                return the_word.entries[the_word.selectedEntryIndex].definition;
              },

            "entries"    : function() {return the_word.entries;},

            "set_selected_entry" : function(i, definition) {
                the_word.entries[i].definition = definition;
                the_word.selectedEntryIndex = i;
            },

            "user_entries" : {
                "get":function() {return user_entries;},
                "add":function() {
                   user_entries[user_entries.length] = 
                           {word : the_word.text, 
                            text : the_word.entries[the_word.selectedEntryIndex].text, 
                            index: (the_word.selectedEntryIndex + 1)};
                }}
          };
    });

var UserEntriesController = function($scope, $http, uws) {
    $scope.entries = uws.user_entries.get();
    $scope.entry = function(e) {
        $http.get("/dict/" + e.word + "[" + e.index + "]")
                .success(function(w){uws.set_word(w);});
    };
};

var DictionaryController = function($scope, $sce, $http, uws) {

    $scope.definition = function() {
        return $sce.trustAsHtml(uws.definition());
    };

    $scope.entries = function() {return uws.entries();};

    $scope.search = function() {
        $http.get("/dict/" + search_term.value)
                .success(function(w){uws.set_word(w);});
    };

    $scope.entry = function(i) {
        $http.get("/dict/" + uws.word().text + "[" + (i + 1) + "]")
                .success(function(w) {
            uws.set_selected_entry(i, w.entries[i].definition);
        });
    };

    $scope.add_to_user_entries = function() {
        uws.user_entries.add();
    };

};

